/**
 * @author 徐楠
 * @date 2022/4/25 7:55
 * @version 1.0
 */

package com.xunan.likou;

import java.util.*;

public class AlphabeticWordGrouping {
    public static void main(String[] args) {
        String[] strs ={"eat", "tea", "tan", "ate", "nat", "bat"};
        List<List<String>> lists = groupAnagrams(strs);
        for (List<String> list : lists) {
            for (String s : list) {
                System.out.println(s);
            }
        }
    }

    public static List<List<String>> groupAnagrams(String[] strs) {
        List<List<String>> result = new ArrayList<>();
        Map<String,List<String>> map = new HashMap<>();
        for (String str : strs) {
            char[] a = str.toCharArray();
            Arrays.sort(a);
            String s = new String(a);
            List<String> orDefault = map.getOrDefault(new String(a), new ArrayList<>());
            orDefault.add(str);
            map.put(s,orDefault);
        }
        Set<Map.Entry<String, List<String>>> entries = map.entrySet();
        for (Map.Entry<String, List<String>> entry : entries) {
            result.add(entry.getValue());
        }
        return result;
    }
}
